# -*- coding:utf-8 -*-
import datetime
import json
import traceback
import uuid

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, auth
from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt

from .forms import UserForm
from .models import UserProfile, UserPaymentLog
from  django.http import JsonResponse
import xlwt
import xlrd
import csv
from io import StringIO
import os
from itertools import islice
@csrf_exempt
def vip_inquire(request):
    result = request.POST.get('result')
    in_timer = datetime.datetime.now()
    vip = False
    user_obj = UserProfile.objects.filter(car_number__iexact=result, expire_at__gte=in_timer)
    if user_obj:
        vip = user_obj.vip
    return HttpResponse(vip)


@login_required()
# @permission_required
def user_list(request):
    """
    用户列表
    :param request:
    :return:
    """
    now = datetime.datetime.now()
    params = {'user_list': UserProfile.objects.filter(isadmin=False),
              'is_active_count': UserProfile.objects.filter(expire_at__gte=now).count()}
    # params['user_list'] = UserProfile.objects.filter()
    return render(request, 'users/user_list.html', params)

@login_required()
# @permission_required
def user_init(request):
    """
    用户导入页面展示
    :param request:
    :return:
    """
    now = datetime.datetime.now()
    params = {'user_list': '',
              'is_active_count': UserProfile.objects.filter(expire_at__gte=now).count()}
    # params['user_list'] = UserProfile.objects.filter()
    return render(request, 'users/user_init.html', params)

def up_xls(request):
    """
    用户导入页面展示
    讲csv或者xls转化成
    json后输出给前段
    :param request:
    :return:
    """
    try:
        file = request.FILES.get('file','')
        file_type = file.name.split(".")
        file_type = file_type[-1]
        file_line=[]
        if file_type == 'xls':
            code= 300
            wb = xlrd.open_workbook(
                filename=None, file_contents=file.read())
            table = wb.sheets()[0]
            row = table.nrows
            for i in range(1, row):
                user = dict()
                col = table.row_values(i)
                user['name'] = col[1]
                user['car_number'] = col[2]
                user['phone'] = col[3]
                user['vip'] = col[4]
                user['address'] = col[5]
                user['create_at'] = col[6]
                user['expire_at'] = col[7]
                file_line.append(user)
        else:
            code =200
            date = StringIO(file.read().decode('ascii', 'ignore'))
            csv_reader = csv.reader(date)
            for i in islice(csv_reader,1,None):
                user = dict()
                user['name'] = i[1]
                user['car_number'] = i[2]
                user['phone'] = i[3]
                user['vip'] = i[4]
                user['address'] = i[5]
                user['create_at'] = i[6]
                user['expire_at'] = i[7]
                file_line.append(user)
    except:
        code = 500
        file_line = ''
    # params['user_list'] = UserProfile.objects.filter()
    return JsonResponse({'code':code,'date':file_line})

@login_required()
# @permission_required
def user_out(request):
    """
    导出页的初始模板
    :param request:
    :return:
    """
    now = datetime.datetime.now()
    params = {'user_list': UserProfile.objects.filter(isadmin=False),
              'is_active_count': UserProfile.objects.filter(expire_at__gte=now).count()}
    # params['user_list'] = UserProfile.objects.filter()
    return render(request, 'users/user_out.html', params)

@login_required()
# @permission_required
def out_xls(request):

    """
    从前端页面传输过来not_out->即选择不导出的ID号,
    然后通过筛选输出成xls
    :param request:
    :return:
    """

    data = request.GET.get('not_out','')

    if data:
        not_out = data.split(',')
        user_list = UserProfile.objects.exclude(id__in=not_out).filter(isadmin=False)
    else:
        user_list = UserProfile.objects.filter(isadmin=False)
    ws = xlwt.Workbook(encoding='utf-8')
    w = ws.add_sheet('评论完成', cell_overwrite_ok=True)
    w.write(0, 0, "序号")
    w.write(0, 1, "用户姓名")
    w.write(0, 2, "车牌号")
    w.write(0, 3, "手机")
    w.write(0, 4, "是否VIP")
    w.write(0, 5, "地址")
    w.write(0, 6, "注册时间")
    w.write(0, 7, "有效期截止时间")
    excel_row = 1
    for i in user_list:
        num = excel_row
        name = i.name
        car_number = i.car_number
        phone = i.phone
        vip = '是' if i.vip else '否'
        address = i.address
        create_at = i.create_at.strftime("%Y-%m-%d %H:%I %p") if i.create_at else ''
        expire_at = i.expire_at.strftime("%Y-%m-%d %H:%I %P") if i.expire_at else ''
        w.write(excel_row, 0, num)
        w.write(excel_row, 1, name)
        w.write(excel_row, 2, car_number)
        w.write(excel_row, 3, phone)
        w.write(excel_row, 4, vip)
        w.write(excel_row, 5, address)
        w.write(excel_row, 6, create_at)
        w.write(excel_row, 7, expire_at)
        excel_row += 1
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=example.xls'
    ws.save(response)
    return response

@login_required()
# @permission_required
def user_now_up(request):
    """
    上传文件
    """
    try:
        code =200
        data = request.POST.get('data','')
        if data:
            data = json.loads(data)
            for i in data:
                userprofile = UserProfile.objects.filter(car_number=i[1]).first()
                # 更新时，以车牌为用户标识
                if userprofile:
                    # 若用户存在，且用户为老用户，则更新字段
                    userprofile.name = i[0]
                    userprofile.car_number = i[1].replace(' ', '')
                    userprofile.phone = i[2]
                    userprofile.address = i[3]
                    userprofile.vip =1 if i[4]=='是' else 0
                    # expire_at = form.cleaned_data['expire_at']
                    userprofile.save()
                else:
                    #用户不存在,则新增一个用户
                    user = User.objects.create(username=uuid.uuid1())
                    vip = 1 if i[4]=='是' else 0
                    UserProfile.objects.create(user=user, name=i[0], car_number=i[1].replace(' ', ''),
                                               phone=i[2], address=i[3], vip=vip,
                                               # expire_at=expire_at,
                                               isadmin=False)
    except:
        code = 300

    return JsonResponse({'code': code})
@login_required()
# @permission_required
def user_form(request):
    """
    新增和编辑用户
    :param request:
    :return:
    """
    if request.method == 'POST':
        params = {}
        user_id = request.GET.get('id')
        form = UserForm(request.POST)
        if user_id and form.is_valid():
            # update
            userprofile = UserProfile.objects.filter(car_number=form.cleaned_data['car_number']).first()
            # 更新时，以车牌为用户标识
            if userprofile:
                # 若用户存在，且用户为老用户，则更新字段
                userprofile.name = form.cleaned_data['name']
                userprofile.car_number = form.cleaned_data['car_number'].replace(' ', '')
                userprofile.phone = form.cleaned_data['phone']
                userprofile.address = form.cleaned_data['address']
                userprofile.vip = form.cleaned_data['vip']
                # expire_at = form.cleaned_data['expire_at']
                userprofile.save()
            else:
                return render(request, 'users/user_form.html', {'errors': ['没有此用户']})
        elif form.is_valid():
            # add
            name = form.cleaned_data['name']
            car_number = form.cleaned_data['car_number'].replace(' ', '')
            phone = form.cleaned_data['phone']
            address = form.cleaned_data['address']
            vip = form.cleaned_data['vip']
            # expire_at = form.cleaned_data['expire_at']
            userprofile = UserProfile.objects.filter(car_number=car_number).first()
            if userprofile:
                # 若用户存在，说明用户已注册此车场，不得再次注册
                params['userform'] = form
                params['errors'] = {'unique': '此用户已注册本车场，不能重复注册！'}
                return render(request, 'users/user_form.html', params)
            else:
                # 若用户不存在， 则新创建用户和关联关系
                user = User.objects.create(username=uuid.uuid1())
                UserProfile.objects.create(user=user, name=name, car_number=car_number.replace(' ', ''),
                                           phone=phone, address=address, vip=vip,
                                           # expire_at=expire_at,
                                           isadmin=False)
        else:
            return render(request, 'users/user_form.html', {'errors': form.errors})
        return HttpResponseRedirect('/user/list/')
    else:
        params = {}
        user_id = request.GET.get('id')
        if user_id:
            userprofile = UserProfile.objects.get(id=user_id)
            data = {
                'name': userprofile.name,
                'car_number': userprofile.car_number,
                'phone': userprofile.phone,
                'address': userprofile.address,
                'vip': userprofile.vip
                # 'expire_at': userprofile.expire_at
            }
            userform = UserForm(initial=data)
        else:
            userform = UserForm()
        params['userform'] = userform
        return render(request, 'users/user_form.html', params)


@login_required()
# @permission_required
def user_remove(request):
    """
    :param request:
    :return:
    """
    params = {}
    user_id = request.POST.get('id')
    # print(user_id)
    try:
        userprofile = UserProfile.objects.get(id=user_id)
        userprofile.user.delete()
        userprofile.delete()
        params['status'] = 1
    except Exception as e:
        traceback.print_exc()
        params['status'] = 0
        params['msg'] = e.args[0]
    return HttpResponse(json.dumps(params))


@login_required()
def user_payment(request):
    """ 用户缴费 """
    context = {}
    if request.method == 'GET':
        user_id = request.GET.get('id')
        payment_list = UserPaymentLog.objects.filter(user_id=user_id).order_by('-payment_at')
        user = UserProfile.objects.get(id=user_id)
        context['user'] = user
        context['payment_list'] = payment_list
        return render(request, 'users/user_payment_log.html', context)
    else:
        user_id = request.POST.get('user_id')
        user_pay = request.POST.get('user_pay')
        start_time = request.POST.get('start_at')
        end_time = request.POST.get('end_at')
        try:
            user = UserProfile.objects.get(id=user_id)
            if user:
                UserPaymentLog.objects.create(
                    user=user,
                    payment_amount=user_pay,
                    start_time=start_time,
                    end_time=end_time
                )
                user.expire_at = end_time
                user.save()
                context['status'] = 1
            else:
                context['status'] = 0
                context['message'] = '无此用户'
        except Exception as err:
            context['status'] = 0
            context['message'] = str(err)
        return HttpResponse(json.dumps(context))


@login_required
def change_pwd(request):
    context = {'status': 0}
    if request.method == 'POST':
        old = request.POST.get('old_password')
        new = request.POST.get('new_password')
        confirm = request.POST.get('confirm_password')
        is_empty = all([old, new, confirm])
        if not is_empty:
            context['status_msg'] = '输入不能为空.'
        elif new != confirm:
            context['status_msg'] = '新密码输入不一致.'
        else:
            user = auth.authenticate(username=request.user.username, password=old)
            if user and user.is_active:
                user.set_password(new)
                user.save()
                context['status'] = 1
            else:
                context['status_msg'] = '用户名或密码错误！'
    return render(request, 'users/user_change_pwd.html', context)
